<template>
  <view class="body">
    <up-steps class="steps-x" :current="state.steps" activeColor="#00D1B6" inactiveColor="#999999">
      <up-steps-item title="基本情况" />
      <up-steps-item title="患病情况" />
      <up-steps-item title="生活方式" />
      <up-steps-item title="补充信息" />
      <up-steps-item title="问卷提交" />
    </up-steps>
    <scroll-view
      v-if="state.steps == 1 || state.steps == 2"
      :scroll-with-animation="true"
      @scroll="scrollX"
      :scroll-left="scrollLeft"
      class="scroll-X"
      scroll-x="true"
    >
      <view class="tabList">
        <view
          :class="['item', state.tabActive == index ? 'on' : '']"
          v-for="(item, index) in state.steps == 1 ? state.tabList : state.tabList2"
          :key="index"
          @tap="tabFun(index)"
        >
          <text class="text">{{ item }}</text>
        </view>
      </view>
    </scroll-view>
    <view v-if="state.questionList.length == 0" class="no_data"> 暂无问卷 </view>
    <view
      v-if="state.steps != 4"
      :class="['wrap', state.steps == 1 || state.steps == 2 ? 'small_height' : '']"
    >
      <view v-if="state.steps == 0" class="questionList">
        <scroll-view
          :scroll-top="scrollTop"
          @scroll="scroll"
          :scroll-with-animation="true"
          class="scroll-Y"
          scroll-y="true"
        >
          <view
            v-for="(item, index) of state.questionList['基本情况']"
            :key="index"
            :class="['list_item', 'list_item' + index]"
          >
            <view class="list_item_title">
              <view class="nums"
                ><text style="color: #00d1b6">{{ index + 1 }}</text
                >/{{ state.questionList['基本情况']?.length }}</view
              >
              <view :class="['tag', item.questionType == '单选' ? '' : 'check']">{{
                item.questionType
              }}</view>
              <view class="title">{{ item.questionName }}</view>
            </view>
            <text v-if="item.remark" class="remark">
              {{ item.remark }}
            </text>
            <view class="answer">
              <view
                v-for="(i, idx) of item.options"
                :key="idx"
                @tap="select(i, item)"
                :class="['answer_item', i.check ? 'on' : '']"
              >
                {{ i.label }}
              </view>
            </view>
          </view>
          <view style="height: 12rpx" />
        </scroll-view>
      </view>
      <view v-if="state.steps == 1" class="questionList">
        <scroll-view
          :scroll-top="scrollTop"
          @scroll="scroll"
          :scroll-with-animation="true"
          class="scroll-Y small_height"
          scroll-y="true"
        >
          <view
            v-for="(item, index) of state.questionList['患病情况']"
            :key="index"
            :class="['list_item', 'list_item' + index]"
          >
            <view class="list_item_title">
              <view class="nums"
                ><text style="color: #00d1b6">{{ index + 1 }}</text
                >/{{ state.questionList['患病情况']?.length }}</view
              >
              <view :class="['tag', item.questionType == '单选' ? '' : 'check']">{{
                item.questionType
              }}</view>
              <view class="title">{{ item.questionName }}</view>
            </view>
            <text v-if="item.remark" class="remark">
              {{ item.remark }}
            </text>
            <view class="answer">
              <view
                v-for="(i, idx) of item.options"
                :key="idx"
                @tap="select(i, item)"
                :class="['answer_item', i.check ? 'on' : '']"
              >
                {{ i.label }}
              </view>
            </view>
          </view>
          <view style="height: 12rpx" />
        </scroll-view>
      </view>
      <view v-if="state.steps == 2">
        <scroll-view
          :scroll-top="scrollTop"
          @scroll="scroll"
          :scroll-with-animation="true"
          class="scroll-Y small_height"
          scroll-y="true"
        >
          <view
            v-for="(arr_item, arr_index) of lifeList"
            :key="arr_index"
            :class="['list', 'list' + arr_index]"
          >
            <view class="list_title">
              {{
                arr_index == 0
                  ? '膳食摄入'
                  : arr_index == 1
                    ? '饮食习惯'
                    : arr_index == 2
                      ? '运动锻炼'
                      : arr_index == 3
                        ? '吸烟情况'
                        : '饮酒情况'
              }}
            </view>
            <image class="img_bg" src="https://ainengli.hzjrsw.com/jkhx/questionTitleBg.png" />
            <view
              v-for="(item, index) of arr_item"
              :key="index"
              :class="['list_item', 'list_item' + arr_index + index]"
            >
              <view class="list_item_title">
                <view class="nums"
                  ><text style="color: #00d1b6">{{ index + 1 }}</text
                  >/{{ arr_item?.length }}</view
                >
                <view :class="['tag', item.questionType == '单选' ? '' : 'check']">{{
                  item.questionType
                }}</view>
                <view class="title">{{ item.questionName }}</view>
              </view>
              <text v-if="item.remark" class="remark">
                {{ item.remark }}
              </text>
              <view class="answer">
                <view
                  v-for="(i, idx) of item.options"
                  :key="idx"
                  @tap="select(i, item)"
                  :class="['answer_item', i.check ? 'on' : '', i.disabled ? 'disabled' : '']"
                >
                  {{ i.label }}
                </view>
              </view>
            </view>
          </view>
          <view style="height: 12rpx" />
        </scroll-view>
      </view>
      <view v-if="state.steps == 3" class="questionList">
        <scroll-view
          :scroll-top="scrollTop"
          @scroll="scroll"
          :scroll-with-animation="true"
          class="scroll-Y"
          scroll-y="true"
        >
          <view
            v-for="(item, index) of state.questionList['补充信息']"
            :key="index"
            :class="['list_item', 'list_item' + index]"
          >
            <view class="list_item_title">
              <view class="nums"
                ><text style="color: #00d1b6">{{ index + 1 }}</text
                >/{{ state.questionList['补充信息']?.length }}</view
              >
              <view :class="['tag', item.questionType == '单选' ? '' : 'check']">{{
                item.questionType
              }}</view>
              <view class="title">{{ item.questionName }}</view>
            </view>
            <text v-if="item.remark" class="remark">
              {{ item.remark }}
            </text>
            <view class="answer">
              <view
                v-for="(i, idx) of item.options"
                :key="idx"
                @tap="select(i, item)"
                :class="['answer_item', i.check ? 'on' : '']"
              >
                {{ i.label }}
              </view>
            </view>
          </view>
          <view style="height: 12rpx" />
        </scroll-view>
      </view>
    </view>
    <view v-if="state.steps == 4" class="finish">
      <view class="finish_title">您已完成所有问卷问题的填写，确认提交问卷？</view>
      <view class="list">
        <view class="item">
          <image class="imgs" src="@/static/image/finish.png" />
          <view class="title">基本情况</view>
          <view class="detail" @tap="lookDetail(0)">查看详情</view>
        </view>
        <view class="item">
          <image class="imgs" src="@/static/image/finish.png" />
          <view class="title">患病情况</view>
          <view class="detail" @tap="lookDetail(1)">查看详情</view>
        </view>
        <view class="item">
          <image class="imgs" src="@/static/image/finish.png" />
          <view class="title">生活方式</view>
          <view class="detail" @tap="lookDetail(2)">查看详情</view>
        </view>
        <view class="item">
          <image class="imgs" src="@/static/image/finish.png" />
          <view class="title">补充信息</view>
          <view class="detail" @tap="lookDetail(3)">查看详情</view>
        </view>
      </view>
    </view>
    <view class="fixed">
      <button v-if="state.steps != 0 && state.steps != 4" class="pre_btn" @tap="prev()">
        上一步
      </button>
      <button v-if="state.steps != 4" class="next_btn" @tap="next()">下一步</button>
      <button v-if="state.steps == 4" class="next_btn" @tap="confirm()">确认提交</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { reactive, ref, watch, nextTick } from 'vue'
import { scale_info_assess, scale_save } from '@/api/questionaire'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { debounce, throttle, deepCopy } from '@/utils/tools'
import store from '@/store'

const state = reactive({
  steps: 0,
  tabActive: 0,
  tabList: ['本人', '父亲', '母亲', '祖父母', '外祖父母'],
  tabList2: ['膳食摄入', '饮食习惯', '运动锻炼', '吸烟情况', '饮酒情况'],
  questionList: [],
  questionInfo: {}
})
const userInfo = ref({})
const lifeList = ref([])

const scrollTop = ref(0)
const scrollLeft = ref(0)
const stepChange = ref(false)
const distanceArr = ref([])
const sonArr = ref([])
let currentId = ''

onShow(() => {
  userInfo.value = JSON.parse(uni.getStorageSync('userInfo'))
  if (!currentId || currentId !== userInfo.value.patientInfo.empi) {
    currentId = deepCopy(userInfo.value.patientInfo.empi)
    // currentId = '74567895'
    init()
  }
})

watch(
  () => state.steps,
  (n, o) => {
    state.tabActive = 0
    scrollTop.value = 0
    stepChange.value = true
    setTimeout(() => {
      stepChange.value = false
    }, 200)
    if (n === 1) {
      distanceArr.value = []
      nextTick(() => {
        state.questionList['患病情况'].forEach((item, index) => {
          getHeight('.list_item' + index).then((height) => {
            distanceArr.value.push(height - 133)
          })
        })
      })
    }
    if (n === 2) {
      distanceArr.value = []
      sonArr.value = []
      nextTick(() => {
        lifeList.value.forEach((item, index) => {
          getHeight('.list' + index).then((height) => {
            distanceArr.value.push(height - 133)
          })
          const arr = []
          item.forEach((val, idx) => {
            getHeight('.list_item' + index + idx).then((height) => {
              arr.push(height - 133)
            })
          })
          sonArr.value.push(arr)
        })
      })
    }
    if (n === 3) {
      distanceArr.value = []
      nextTick(() => {
        state.questionList['补充信息'].forEach((item, index) => {
          getHeight('.list_item' + index).then((height) => {
            distanceArr.value.push(height - 87)
          })
        })
      })
    }
  },
  { immediate: true }
)
watch(
  () => state.tabActive,
  (n, o) => {
    if (n === 3 || n === 4) {
      scrollLeft.value = 155
    } else {
      scrollLeft.value = 0
    }
  },
  { immediate: true, deep: true }
)

const init = async () => {
  await scale_info_assess({ empi: currentId, userId: userInfo.value.userId }).then((res) => {
    if (res.code === 0) {
      state.questionInfo = res.data
      const arr = JSON.parse(res.data.questions)
      // 生活方式列表lifeList
      if (
        arr['膳食摄入'] &&
        arr['饮食习惯'] &&
        arr['运动锻炼'] &&
        arr['吸烟情况'] &&
        arr['饮酒情况']
      ) {
        lifeList.value.push(arr['膳食摄入'])
        lifeList.value.push(arr['饮食习惯'])
        lifeList.value.push(arr['运动锻炼'])
        lifeList.value.push(arr['吸烟情况'])
        lifeList.value.push(arr['饮酒情况'])
      }
      for (const value in arr) {
        if (Object.prototype.hasOwnProperty.call(arr, value)) {
          arr[value].forEach((val) => {
            // 格式化选项并添加是否选中状态
            val.options = JSON.parse(val.options)
            val.options.forEach((item) => {
              item.check = false
            })
          })
        }
      }
      state.questionList = arr
    }
  })
  nextTick(() => {
    state.questionList['基本情况'].forEach((item, index) => {
      getHeight('.list_item' + index).then((height) => {
        distanceArr.value.push(height - 87)
      })
    })
  })
}
const tabFun = (index) => {
  // tab切换
  state.tabActive = index
  scrollTop.value = distanceArr.value[index] || 0
}

const getHeight = (str: string) => {
  return new Promise((resolve, reject) => {
    const query = uni.createSelectorQuery()
    query
      .select(str)
      .boundingClientRect((data) => {
        resolve(data.top)
      })
      .exec()
  })
}

const select = (item: any, val: number) => {
  if (item.disabled) {
    return
  }
  if (val.questionType == '单选') {
    // 单选逻辑
    val.options.forEach((i) => {
      i.check = false
    })
    val.chosen = item.value
    // 吸烟与喝酒选择从不时禁用其他选项
    if (val.questionName == '吸烟状态') {
      lifeList.value[3][1].options.forEach((i) => {
        if (item.value == '从不') {
          lifeList.value[3][1].chosen = null
          i.check = false
          i.disabled = true
        } else {
          i.disabled = false
        }
      })
      lifeList.value[3][2].options.forEach((i) => {
        if (item.value == '从不') {
          lifeList.value[3][2].chosen = null
          i.check = false
          i.disabled = true
        } else {
          i.disabled = false
        }
      })
    }
    if (val.questionName == '当前饮酒情况') {
      lifeList.value[4][1].options.forEach((i) => {
        if (item.value == '从不') {
          lifeList.value[4][1].chosen = null
          i.check = false
          i.disabled = true
        } else {
          i.disabled = false
        }
      })
      lifeList.value[4][2].options.forEach((i) => {
        if (item.value == '从不') {
          lifeList.value[4][2].chosen = null
          i.check = false
          i.disabled = true
        } else {
          i.disabled = false
        }
      })
      lifeList.value[4][3].options.forEach((i) => {
        if (item.value == '从不') {
          lifeList.value[4][3].chosen = null
          i.check = false
          i.disabled = true
        } else {
          i.disabled = false
        }
      })
    }
  } else {
    // 多选选逻辑
    if (!val.chosen) {
      val.chosen = item.value
    } else {
      if (!item.check) {
        val.chosen = val.chosen + ',' + item.value
      } else {
        val.chosen = val.chosen.replace(item.value + ',', '')
        val.chosen = val.chosen.replace(',' + item.value, '')
        val.chosen = val.chosen.replace(item.value, '')
      }
    }
  }
  item.check = !item.check
}

const lookDetail = (index: number) => {
  state.steps = index
}

const prev = () => {
  state.steps--
  scrollTop.value = 0
  state.tabActive = 0
  scrollLeft.value = 0
}
const next = () => {
  let canGoNext = true
  if (state.steps === 0) {
    for (const item of state.questionList['基本情况']) {
      if (!item.chosen) {
        // 提示并滚动到对应题目位置
        canGoNext = false
        const index = state.questionList['基本情况']
          .map((e) => e.questionCode)
          .indexOf(item.questionCode)
        scrollTop.value = distanceArr.value[index] || 0
        uni.showToast({
          title: '请选择' + item.questionName,
          icon: 'none'
        })
        break
      }
    }
  } else if (state.steps === 1) {
    for (const item of state.questionList['患病情况']) {
      if (!item.chosen) {
        // 提示并滚动到对应题目位置
        canGoNext = false
        const index = state.questionList['患病情况']
          .map((e) => e.questionCode)
          .indexOf(item.questionCode)
        scrollTop.value = distanceArr.value[index] || 0
        uni.showToast({
          title: '请选择' + item.questionName,
          icon: 'none'
        })
        break
      }
    }
  } else if (state.steps === 2) {
    let isEmpty = false
    let i = 0
    for (const val of lifeList.value) {
      for (const item of val) {
        if (!item.chosen && !item.options[0].disabled) {
          isEmpty = true
          canGoNext = false
          const index = val.map((e) => e.questionCode).indexOf(item.questionCode)
          scrollTop.value = sonArr.value[i][index] || 0
          uni.showToast({
            title: '请选择' + item.questionName,
            icon: 'none'
          })
          break
        }
      }
      if (isEmpty) {
        break
      } else {
        i++
      }
    }
  } else if (state.steps === 3) {
    for (const item of state.questionList['补充信息']) {
      if (!item.chosen) {
        // 提示并滚动到对应题目位置
        canGoNext = false
        const index = state.questionList['补充信息']
          .map((e) => e.questionCode)
          .indexOf(item.questionCode)
        scrollTop.value = distanceArr.value[index] || 0
        uni.showToast({
          title: '请选择' + item.questionName,
          icon: 'none'
        })
        break
      }
    }
  }
  if (canGoNext) {
    state.steps++
    scrollTop.value = 0
    state.tabActive = 0
    scrollLeft.value = 0
    if (state.steps == 4) {
      state.questionList['膳食摄入'] = lifeList.value[0]
      state.questionList['饮食习惯'] = lifeList.value[1]
      state.questionList['运动锻炼'] = lifeList.value[2]
      state.questionList['吸烟情况'] = lifeList.value[3]
      state.questionList['饮酒情况'] = lifeList.value[4]
      store.commit('SET_QUESTIONAIRE', state.questionList)
    }
  }
}
const confirm = () => {
  const params = {
    id: state.questionInfo.id,
    userId: userInfo.value.userId,
    empi: currentId,
    integrity: state.questionInfo.integrity,
    scaleCode: state.questionInfo.scaleCode,
    riskElements: state.questionInfo.riskElements,
    questions: '',
    answers: JSON.stringify(state.questionList),
    isFinish: true,
    score: 0
  }
  uni.showLoading({
    title: '正在解读中...',
    mask: true
  })
  scale_save(params).then((res) => {
    if (res.code == 0) {
      userInfo.value.patientInfo.questionState = true
      store.commit('SET_USERINFO', userInfo.value)
      uni.hideLoading()
      uni.showToast({
        title: '问卷提交成功，请等待健康管理报告生成',
        icon: 'none',
        duration: 2000,
        success: () => {
          setTimeout(() => {
            uni.switchTab({
              url: '/pages/index/index'
            })
          }, 2000)
        }
      })
    }
  })
}
const scroll = debounce(
  (e) => {
    // if (!stepChange.value) {
    //   scrollTop.value = e.detail.scrollTop
    // }
    if (state.tabActive <= 0) {
      // 在未显示tab并且 currentTab <= 0时，防止uview ui抖动bug，设置默认复位值
      state.tabActive = 0
    }
    nextTick(() => {
      const length = distanceArr.value.length
      const index = distanceArr.value.findIndex((el) => el - e.detail.scrollTop > 8)
      // 当index  == -1 的时候，实际当前滚动的距离超出了最大值，也就是在最后一个tab显示的内容
      // 当index > 0 的时候，说明能在当前的scrollTop值找到，即index的前一位
      state.tabActive = index > 0 ? index - 1 : length - 1
      if (index == 0) {
        state.tabActive = 0
      }
    })
  },
  200,
  ''
)
const scrollX = debounce(
  (e) => {
    scrollLeft.value = e.detail.scrollLeft
  },
  200,
  ''
)
</script>

<style lang="scss" scoped>
.body {
  height: 100%;
  // 步骤条样式
  ::v-deep .u-steps {
    align-items: center;
    height: 140rpx;
    background: #fff;
  }

  ::v-deep .uicon-checkmark {
    font-size: 24rpx !important;
  }

  ::v-deep .u-steps-item__wrapper__circle__text {
    // transform: translateY(-2rpx);
  }

  ::v-deep .u-steps-item__line {
    height: 1rpx !important;
  }

  ::v-deep .u-steps-item__content {
    margin: 0 !important;
    margin-top: 16rpx !important;

    .u-text__value {
      font-size: 28rpx !important;
    }

    .u-text__value--main {
      color: #00d1b6;
    }

    .u-text__value--content {
      color: #999;
    }
  }

  .no_data {
    margin-top: 200rpx;
    font-size: 32rpx;
    font-weight: 400;
    color: #666;
    text-align: center;
  }

  .scroll-X {
    box-sizing: border-box;
    width: 100%;
    margin: 16rpx 0;
    overflow-x: scroll;
    background: #f3f7f8;

    .tabList {
      white-space: nowrap;

      .item {
        position: relative;
        display: inline-block;
        height: 64rpx;
        padding: 0 30rpx;
        margin-left: 32rpx;
        font-size: 28rpx;
        line-height: 64rpx;
        color: #222;
        text-align: center;
        vertical-align: middle;
        background: #fff;
        border-radius: 32rpx;

        &:nth-last-child(1) {
          margin-right: 32rpx;
        }

        &.on {
          font-weight: 700;
          color: #fff;
          background: #00d1b6;
        }
      }
    }
  }

  .wrap {
    height: calc(100vh - 340rpx);
    // margin-top: 32rpx;
    padding: 32rpx;
    padding-top: 0;
    overflow-y: hidden;

    .scroll-Y {
      height: calc(100vh - 336rpx);

      &.small_height {
        height: calc(100vh - 428rpx);
      }
    }

    .list {
      position: relative;
      overflow: hidden;

      &:first-child {
        margin-top: 32rpx;
      }
    }

    .list_title {
      margin: 26rpx 28rpx 22rpx;
      font-size: 32rpx;
      font-weight: 600;
      color: #fff;
    }

    .img_bg {
      position: absolute;
      top: 0;
      left: 0;
      z-index: -1;
      width: 686rpx;
      height: 208rpx;
    }

    .list_item {
      padding: 32rpx;
      margin-bottom: 24rpx;
      background: #fff;
      border-radius: 16rpx;

      &:first-child {
        margin-top: 32rpx;
      }

      .list_item_title {
        display: flex;
        gap: 8rpx;
        align-items: top;
        justify-content: flex-start;

        .nums {
          font-size: 24rpx;
          font-weight: 500;
          color: #666;
          transform: translateY(4rpx);
        }

        .tag {
          width: 80rpx;
          height: 40rpx;
          font-size: 24rpx;
          font-weight: 500;
          line-height: 40rpx;
          color: #fff;
          text-align: center;
          background: #02bcc3;
          border-radius: 4rpx;
        }

        .check {
          background: #5c8eff;
        }

        .title {
          width: 480rpx;
          font-size: 32rpx;
          font-weight: 500;
          color: #222;
          transform: translateY(-4rpx);
        }
      }

      .remark {
        display: inline-block;
        margin-top: 16rpx;
        margin-left: 8rpx;
        font-size: 24rpx;
        font-weight: 400;
        color: #999;
        text-align: justify;
      }

      .answer {
        display: flex;
        flex-wrap: wrap;
        gap: 16rpx;
        justify-content: space-between;
        margin-top: 32rpx;

        .answer_item {
          box-sizing: border-box;
          width: 48%;
          padding: 16rpx 30rpx;
          font-size: 28rpx;
          font-weight: 400;
          color: #222;
          text-align: left;
          background: #fafafa;
          border: 1rpx solid #fafafa;
          border-radius: 8rpx;
          transform: rotateZ(360deg);

          &.on {
            font-size: 28rpx;
            font-weight: 500;
            color: #00d1b6;
            background: rgb(0 209 182 / 10%);
            border: 1rpx solid #00d1b6;
            border-radius: 8rpx;
          }

          &.disabled {
            color: #999;
            background: #f5f5f5;
          }
        }
      }
    }
  }

  .finish {
    padding: 32rpx;
    margin: 24rpx 32rpx;
    background: #fff;
    border-radius: 16rpx;

    .finish_title {
      padding-bottom: 32rpx;
      font-size: 32rpx;
      font-weight: 600;
      color: #222;
      border-bottom: 1rpx solid #e5e6eb;
    }

    .list {
      .item {
        display: flex;
        align-items: center;
        justify-content: flex-start;
        margin-top: 32rpx;

        .imgs {
          width: 40rpx;
          height: 40rpx;
        }

        .title {
          margin-left: 16rpx;
          font-size: 32rpx;
          font-weight: 500;
          color: #222;
        }

        .detail {
          width: 152rpx;
          height: 56rpx;
          margin-left: 48rpx;
          font-size: 26rpx;
          font-weight: 400;
          line-height: 56rpx;
          color: #00d1b6;
          text-align: center;
          border: 1rpx solid #00d1b6;
          border-radius: 38rpx;
        }
      }
    }
  }

  .fixed {
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 10;
    box-sizing: border-box;
    display: flex;
    gap: 24rpx;
    justify-content: space-between;
    width: 100%;
    padding: 24rpx 32rpx;
    padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
    background: #fff;
    border-top: 1rpx solid #e5e6eb;

    .pre_btn {
      width: 100%;
      font-size: 32rpx;
      font-weight: 500;
      color: #00d1b6;
      background: #fff;
      border: 1rpx solid #00d1b6;
      border-radius: 44rpx;
    }

    .next_btn {
      width: 100%;
      font-size: 32rpx;
      font-weight: 500;
      color: #fff;
      background: #00d1b6;
      border-radius: 44rpx;
    }
  }
}
</style>
